/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Simon
 */
public class FlashFilter implements Filter {

    private static final boolean debug = true;

    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;

    public FlashFilter() {

    } 

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            String flash = (String) ((HttpServletRequest)request).getSession().getAttribute("flash");
            if (flash != null && !flash.isEmpty()) {
                request.setAttribute("flash", flash);
                ((HttpServletRequest)request).getSession().removeAttribute("flash");
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
	if (filterConfig == null) return ("FlashFilter()");
	StringBuffer sb = new StringBuffer("FlashFilter(");
	sb.append(filterConfig);
	sb.append(")");
	return (sb.toString());
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void destroy() {
    }

}
